﻿using System;
using System.Windows.Forms;
using Com.OpenCode.Framework.Core;
using DevExpress.Utils;
using DevExpress.XtraBars.Docking2010.Views;
using DevExpress.XtraEditors;

namespace Com.OpenCode.Framework.DevForm
{
    public class DocumentUI : IDockPanel
    {
        private BaseDocument _BaseDocument;
        private BuildItemEventArgs _BuildItemEventArgs;
        private Control _UserControl;

        public DocumentUI(BuildItemEventArgs args)
        {
            args.Plugin.Owner = this;
            _BuildItemEventArgs = args;
            CreateControl();
            _BaseDocument = (_BuildItemEventArgs.Owner as DockManagerUI).TabbedView.Controller.AddDocument(UserControl);
            (_BuildItemEventArgs.Owner as DockManagerUI).TabbedView.Controller.Activate(_BaseDocument);
            _BaseDocument.Caption = args.Plugin.Properties.Get("Text").ToString();
            bool _CanClose = true;
            bool.TryParse(args.Plugin.Properties.Get("CanClose").ToString(), out _CanClose);
            if (_CanClose)
            {
                _BaseDocument.Properties.AllowClose = DefaultBoolean.True;
            }
            else
            {
                _BaseDocument.Properties.AllowClose = DefaultBoolean.False;
            }
            bool _AllowFloat = false;
            bool.TryParse(args.Plugin.Properties.Get("AllowFloat").ToString(), out _AllowFloat);
            if (_AllowFloat)
            {
                _BaseDocument.Properties.AllowFloat = DefaultBoolean.True;
            }
            else
            {
                _BaseDocument.Properties.AllowFloat = DefaultBoolean.False;
            }
            _BaseDocument.Disposed += _BaseDocument_Disposed;
        }

        public virtual Control UserControl
        {
            get { return _UserControl; }
        }

        public void ShowPanel()
        {
            (_BuildItemEventArgs.Owner as DockManagerUI).TabbedView.Controller.Activate(_BaseDocument);
        }

        protected virtual void CreateControl()
        {
            if (_BuildItemEventArgs.Plugin.Properties.Exist("Class"))
            {
                _UserControl = (UserControl)_BuildItemEventArgs.Plugin.Addin.Runtime.CreateObject(_BuildItemEventArgs.Plugin.Properties.GetString("Class"));
            }
            else
            {
                _UserControl = (UserControl)ClassDoozer.BulidItem(_BuildItemEventArgs.Plugin.Addin, _BuildItemEventArgs.Plugin.Properties.GetString("ClassId"));
            }
            if (_UserControl == null)
            {
                _UserControl = new XtraUserControl();
            }
            _UserControl.Dock = DockStyle.Fill;
        }

        private void _BaseDocument_Disposed(object sender, EventArgs e)
        {
            _BuildItemEventArgs.Plugin.Owner = null;
        }
    }
}